<template>
  <el-card class="box-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>诊断成绩换算</span>
      </div>
    </template>
    <div>
      <div class="btn">
        <el-button type="primary" @click="addClick">新增</el-button>
      </div>
      <div class="searchAll">
        <div>
          <!-- <el-cascader
            v-model="tableDataConfig.province"
            :options="cityData"
            @change="(val: any) => getsearchChange('province', val)"
          /> -->
          <el-select
            v-model="tableDataConfig.pid"
            placeholder="请选择省份"
            size="large"
            clearable
            style="width: 240px"
            @change="(val: any) => getsearchChange('province', val)"
          >
            <el-option
              v-for="item in provinceData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-select
            v-model="tableDataConfig.city"
            placeholder="请输入市区"
            size="large"
            clearable
            style="width: 240px"
            @change="(val: any) => getsearchChange('city', val)"
          >
            <el-option
              v-for="item in cityData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-input
            v-model="tableDataConfig.year"
            style="max-width: 323px"
            placeholder="请输入年份"
            clearable
            class="height40"
            @change="getsearchYear"
          >
            <template #append>
              <el-button type="primary" @click="getsearchYear">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      class="margintop"
      stripe
      :header-cell-style="{ 'border-bottom': 'none' }"
      :header-row-style="{ height: '60px' }"
      :cell-style="{ height: '60px', 'border-bottom': 'none' }"
    >
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="times" label="诊断序号" />
      <el-table-column prop="year" label="年份" />
      <el-table-column prop="provinceName" label="省份" />
      <el-table-column prop="city" label="市区" />
      <el-table-column prop="type" label="描述" />
      <el-table-column prop="course" label="选科" />

      <!-- <el-table-column prop="batch" label="批次/二本分数线/权重" /> -->
      <!-- <el-table-column prop="score" label="二本分数线" width="100" />
      <el-table-column prop="weight" label="权重" /> -->
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑"
            placement="top"
          >
            <el-icon
              size="20"
              style="cursor: pointer"
              @click="editChange(scope.row)"
              ><EditPen
            /></el-icon>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-icon
              @click="handleDelete(scope.row)"
              size="20"
              style="cursor: pointer; margin-left: 10px"
              ><Delete
            /></el-icon>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      v-show="tableDataConfig.total > 0"
      v-model:current-page="tableDataConfig.page"
      v-model:page-size="tableDataConfig.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDataConfig.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <Dilog
      v-model:dialogFormVisible="dialogFormVisible"
      :title="title"
      width="1000"
      @handleClick="handleClick"
    >
      <template #center>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
        >
          <el-row class="elRow">
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="省份" prop="pid">
                <el-select
                  v-model="ruleForm.pid"
                  placeholder="请输入省份"
                  size="large"
                  style="width: 240px"
                  @change="($event: any) => addSelect($event, '省')"
                >
                  <el-option
                    v-for="item in provinceData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="市区" prop="city">
                <el-select
                  v-model="ruleForm.city"
                  placeholder="请输入市区"
                  size="large"
                  style="width: 240px"
                  @change="($event: any) => addSelect($event, '市')"
                >
                  <el-option
                    v-for="item in cityData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="年份" prop="year">
                <!-- @change="visibleChange" -->
                <el-input
                  size="large"
                  type="number"
                  v-model="ruleForm.year"
                  style="width: 240px"
                  placeholder="请输入年份"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="elRow">
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="选科" prop="course">
                <!-- 
                 <el-select
                  v-model="ruleForm.course"
                  placeholder="请输入选科"
                  size="large"
                  style="width: 240px"
                  @change="selectChange"
                >
                  <el-option
                    v-for="item in xk"
                    :key="item.id"
                    :label="item.course"
                    :value="item.course"
                  />
                </el-select>
                 -->
                <el-input
                  size="large"
                  v-model="ruleForm.course"
                  style="width: 240px"
                  placeholder="请输入选科"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="诊断序号" prop="times">
                <el-input
                  size="large"
                  v-model="ruleForm.times"
                  style="width: 240px"
                  placeholder="请输入诊断序号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="类型" prop="type">
                <el-input
                  size="large"
                  v-model="ruleForm.type"
                  style="width: 240px"
                  placeholder="请输入类型"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row class="elRow">
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="批次" prop="batch">
                <el-input
                  size="large"
                  v-model="ruleForm.batch"
                  style="width: 240px"
                  placeholder="请输入批次"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7" style="margin-right: 20px">
              <el-form-item label="二本分数线" prop="score">
                <el-input
                  size="large"
                  v-model="ruleForm.score"
                  style="width: 240px"
                  placeholder="请输入二本分数线"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="权重" prop="weight">
                <el-input
                  size="large"
                  v-model="ruleForm.weight"
                  style="width: 240px"
                  placeholder="请输入权重"
                />
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-form-item label="填写信息" class="custom-form-item" prop="scores">
            <JsonEditor
              ref="jsonEditorRef"
              class="el-menu-vertical-demo"
              :options="{ mode: 'form', modes: ['form', 'code'] }"
              :languageDataList="languageDataList"
              v-model="ruleForm.scores"
              :show="false"
              @save-json="saveJson"
            />
          </el-form-item>
        </el-form>
      </template>
    </Dilog>
  </el-card>
</template>
<script lang="ts" setup>
// import {cityData} from "./cityDataJson.js"
import Dilog from '@/components/proDialog/index.vue';
import { ElMessage } from 'element-plus';
import { ref, Ref, reactive, onMounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import * as chinaArea from 'element-china-area-data';
import JsonEditor from '@/components/JsonEditor/index.vue';
import transcript from '@/modules';
const { addApi, delApi, tableDataApi } = transcript; //checkSubAndLineApi
const dialogFormVisible = ref(false);
const loading = ref(false);
const title = ref('新增');
const tableData = ref([]);

const languageDataList = ref([]);

// 类型定义
interface Area {
  value: string;
  label: string;
  children?: Area[];
}
// 使用 Ref 包裹类型
const cityData: Ref<Area[]> = ref([]);
// const provinceList: Ref<Area[]> = ref([]);
const provinceData: Ref<Area[]> = ref([]); //省份信息
const jsonEditorRef = ref<InstanceType<typeof JsonEditor> | null>(null);
const tableDataConfig = ref({
  pageSize: 10,
  page: 1,
  pid: '',
  city: '',
  year: '',
  total: 0,
});
// const lineParams = ref({
//   page: 1,
//   pageSize: 100,
//   provinceCode: '',
//   year: '',
// });
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
  id: '',
  pid: '',
  provinceName: '',
  city: '',
  course: '',
  type: '',
  year: '',
  times: '',
  batch: '',
  score: '',
  scores: '',
  weight: '',
});

interface RuleForm {
  pid: string;
  city: string;
  course: string;
  type: string;
  year: string;
  times: string;
  batch: string;
  score: string;
  weight: string;
  provinceName: string;
  scores: string;
  id?: string;
}

// // 自定义校验函数
// const validateJsonEditor = (rule: any, value: any, callback: any) => {
//   value = languageDataList.value;
//   if (!value || Object.keys(value).length === 0) {
//     callback(new Error('请填写有效的 JSON 数据'));
//   } else {
//     try {
//       JSON.stringify(value); // 验证 JSON 是否正确
//       callback();
//     } catch (error) {
//       callback(new Error('JSON 格式错误，请检查输入'), error);
//     }
//   }
// };

const rules = reactive<FormRules<RuleForm>>({
  pid: [{ required: true, message: '请选择省份', trigger: 'blur' }],
  city: [{ required: true, message: '请选择市区', trigger: 'blur' }],
  course: [{ required: true, message: '请选择科目', trigger: 'blur' }],
  type: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  year: [{ required: true, message: '请输入年份', trigger: 'blur' }],
  times: [{ required: true, message: '请输入诊断序号', trigger: 'blur' }],
  score: [{ required: true, message: '请输入二本分数线', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入权重', trigger: 'blur' }],
});
const addClick = () => {
  Object.assign(ruleForm, {
    id: '',
    pid: '',
    city: '',
    course: '',
    type: '',
    year: '',
    times: '',
    batch: '',
    score: '',
    weight: '',
    scores: '',
  });
  languageDataList.value = [];
  cityData.value = [];
  title.value = '新增';
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
};

const editChange = (row: any) => {
  row.pid = String(row.pid);
  cityData.value = provinceData.value
    ? provinceData.value.find((item) => item.value == row.pid)?.children || []
    : [];
  ruleForm.id = row.id;
  ruleFormRef.value?.clearValidate();
  title.value = '编辑';
  parms.value.pid = row.pid;
  parms.value.year = row.year;
  Object.assign(ruleForm, row);
  dialogFormVisible.value = true;
  languageDataList.value = row.scores ? JSON.parse(row.scores) : {};
};

const handleDelete = async (row: any) => {
  const data = await delApi({ id: row.id });
  if (data.code == 20000) {
    ElMessage({
      message: data.msg,
      type: 'success',
    });
    getTableData();
  }
};
// 分页
const handleSizeChange = (val: any) => {
  tableDataConfig.value.pageSize = val;
  getTableData();
};
const handleCurrentChange = (val: any) => {
  tableDataConfig.value.page = val;
  getTableData();
};
const parms = ref({
  pid: '',
  year: '',
});

// 新增addApi
const addForm = async () => {
  const data = await addApi(ruleForm);
  if (data.code == 20000) {
    ElMessage({
      message: data.msg,
      type: 'success',
    });
  }
  getTableData();
};
// 编辑editApi
const editForm = async () => {
  const data = await addApi(ruleForm);
  if (data.code == 20000) {
    ElMessage({
      message: data.msg,
      type: 'success',
    });
    getTableData();
  }
};
const handleClick = () => {
  // validateJsonEditor();
  ruleFormRef.value?.validate((valid: boolean) => {
    jsonEditorRef.value?.saveJson?.();
    if (valid && ruleForm.scores) {
      const data = provinceData.value.find(
        (item) => item.value == ruleForm.pid
      );
      ruleForm.provinceName = data?.label || '';
      ruleForm.id ? editForm() : addForm();
      dialogFormVisible.value = false;
    } else {
      console.error('请输入内容');
    }
  });
};

const saveJson = (val: any) => {
  if (!val || Object.keys(val).length === 0) {
    ElMessage.error('填写信息不能为空并正确填入信息');
  } else {
    ruleForm.scores = JSON.stringify(val);
  }
};
// 筛选数据
const getsearchChange = (type: string, val: any) => {
  if (type == 'province') {
    tableDataConfig.value.city = '';
    //获取市区的数据
    cityData.value = provinceData.value
      ? provinceData.value.find((item) => item.value == val)?.children || []
      : [];
  } else {
    if (cityData.value.length) {
      const data = cityData.value.find((item) => item.value == val);
      tableDataConfig.value.city = data?.label || '';
    }
  }
  tableDataConfig.value.page = 1;
  getTableData();
};
// 搜索年份
const getsearchYear = () => {
  tableDataConfig.value.page = 1;
  getTableData();
};
// 新增年份的筛选
const addSelect = async (val: any, type: any) => {
  if (type == '省') {
    ruleForm.city = '';
    // ruleForm.year = '';
    parms.value.pid = val;
    cityData.value = provinceData.value
      ? provinceData.value.find((item) => item.value == val)?.children || []
      : [];
  } else if (type == '市') {
    cityData.value = provinceData.value
      ? provinceData.value.find((item) => item.value == ruleForm.pid)
          ?.children || []
      : [];
  }
  //获取市区的数据
};

//列表数据获取
const getTableData = async () => {
  const { data } = await tableDataApi(tableDataConfig.value);
  tableData.value = data.data;
  tableDataConfig.value.total = data.total;
};
onMounted(() => {
  const municipalities = ['北京市', '上海市', '天津市', '重庆市'];
  //获取第三方省份 过滤西藏
  const data = chinaArea.regionData
    .filter((item) => item.label !== '西藏自治区') // 过滤掉“西藏自治区”
    .map((item) => ({
      ...item,
      label: item.label.replace('省', ''), // 去掉“省”字
    }));
  provinceData.value = data.map((item) => {
    if (municipalities.includes(item.label)) {
      return {
        ...item,
        children: [{ ...item }], // 将children改为本身
      };
    }
    return item;
  });
  //获取接口的省份数据
  //   provinceDataList();
  getTableData();
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
